let pageData = {
    "records": [
        {
            "billId": 1,
            "billProductId": 1,
            "billBuyerId": 1,
            "billPrice": 10,
            "billNumber": 2,
            "billCreateTime": "2022-06-05T16:00:00.000+00:00",
            "billStatus": 1,
            "product": {
                "id": 1,
                "categoryId": 1,
                "providerId": 4,
                "name": "百草味 手撕面包1000g/箱 原味整箱办公室早餐休闲食品面包点心零食",
                "stock": 981,
                "price": 22.9,
                "img": "https://img14.360buyimg.com/n1/jfs/t1/196223/7/24898/247568/628370b0E70c316de/7ed05094babd66c0.jpg",
                "detail": "百草味手撕面包（原味)1000g商品毛重：1.0kg商品产地：浙江省杭州市口味：原味包装形式：箱装类别：手撕面包净含量：501g-1kg",
                "createTime": "2018-09-20T20:35:27.000+00:00",
                "status": null,
                "category": null,
                "provider": null
            },
            "buyer": {
                "id": 1,
                "email": "862995359@qq.com",
                "usercode": "woaini",
                "username": "woaini",
                "password": "123456",
                "gender": 1,
                "birthday": "2022-05-17T16:00:00.000+00:00",
                "tel": "13311111111",
                "address": "天津市-天津市-和平区-翻斗花园",
                "salt": null,
                "img": "https://uni1024.oss-cn-hangzhou.aliyuncs.com/mall-system/images/users/woaini/2022-06-021654180300195.jpeg",
                "createTime": null,
                "role": null
            },
            "provider": {
                "id": 2,
                "code": "deli",
                "name": "得力",
                "detail": "得力文具店",
                "contact": "周女士",
                "tel": "13112341234",
                "address": "全国",
                "img": null,
                "status": null,
                "createTime": null
            }
        }
    ],
    "total": 1,
    "size": 5,
    "current": 1,
    "bills": [],
    "optimizeCountSql": true,
    "searchCount": true,
    "countId": null,
    "maxLimit": null,
    "pages": 1
}
let $entry_bill = $('#admin-card-bill-list-entry')
let $entry_pages = $('#admin-card-bill-pages-entry')
function renderBills(bills, delay){
    $entry_bill.html('')
    setTimeout(function (){
        bills.forEach(function (bill, index){
            let fn_modify = "renderModal(" + bill['id'] + ")"
            let fn_show = "renderShowModal(this, " + bill['id'] + ")"
            let fn_remove = "removeBill(" + bill['id'] + ")"
            $entry_bill.append(`
            <tr valign="baseline">
                <td><input type="checkbox" class="cb_bill" data-id="${bill['id']}" style="width: 20px; height: 20px;"></td>
                <td>${bill['id']}</td>
                <td>${bill['provider']['name']}</td>
                <td>${bill['product']['name']}</td>
                <td class="text-danger">￥${bill['price']}</td>
                <td>${ORDER_STATUS[bill['status']]}</td>
                <td>
                     <button class="btn btn-primary w-25" data-bs-toggle="modal" data-bs-target="#modal-show" onclick="${fn_show}">查看</button>
                       <div class="btn-group d-inline" role="group">
                        <button type="button" class="btn btn-warning dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                          编辑
                        </button>
                        <ul class="dropdown-menu" aria-labelledby="btnGroupDrop1">
                          <li><button class="dropdown-item" onclick="updateProductStatus(${bill['id']}, 0)">待结算</button></li>
                          <li><button class="dropdown-item" onclick="updateProductStatus(${bill['id']}, 1)">待发货</button></li>
                          <li><button class="dropdown-item" onclick="updateProductStatus(${bill['id']}, 2)">运输中</button></li>
                          <li><button class="dropdown-item" onclick="updateProductStatus(${bill['id']}, 3)">待确认收货</button></li>
                          <li><button class="dropdown-item" onclick="updateProductStatus(${bill['id']}, 4)">已收货</button></li>
                        </ul>
                      </div>
                     <button class="btn btn-danger w-25" data-bs-toggle="modal" data-bs-target="#modal-base" onclick="${fn_remove}">删除</button>
                </td>
          </tr>
        `)
        })
    }, delay)
}
// 渲染分页
function renderPage(page){
    $entry_pages.html('')
    let $perPage = $(`<li></li>`)
    // 渲染尾部
    let $tail = `<li class="align-self-center r">
                &nbsp;&nbsp;到第&nbsp;&nbsp;
            </li>
            <li class="align-self-center">
                <input id="admin-user-input-to-page" class="input-group" name="pageNum" size="5">
            </li>
            <li class="align-self-center">
                &nbsp;页&nbsp;
            </li>
            <li class="align-self-center">
                <button class="btn btn-outline-dark" onclick="toPage('admin-user-input-to-page', 1, ${page.pages})">确定</button>
            </li>`
    // 计算页数的渲染范围
    page.prePage = Math.max(1, page['current']- 1)
    page.nextPage = Math.min(page['pages'], page['current'] + 1)
    page.startPage = Math.max(1, page['current'] - 2)
    page.endPage = Math.min(page['pages'], page['current'] + 2)
    // 渲染每一页
    for (let i = page.startPage; i <= page.endPage; i++) {
        if(i === page.current){ // 渲染当前页，设置一个高亮的效果
            $perPage.append(`
            <li class="page-item mx-2 active" aria-current="page">
             <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
         </li>`)
        } else {
            $perPage.append(`
             <li class="page-item mx-2" aria-current="page">
                 <a class="page-link d-block" href="${paramUpdateCurrentParam('pageNum', i)}">${i}</a>
             </li>`
            )
        }
    }
    $entry_pages.html('')
    $entry_pages.html(`
            <ul class="pagination mx-auto justify-content-center">
            <li class="align-self-center me-3 rounded-3">
                    第 ${page.current} 页 &nbsp;&nbsp; 共 ${page.pages} 页
            </li>
            <li class="page-item ms-page">
                 <a class="page-link" href="${paramUpdateCurrentParam('pageNum', 1)}">
                    首页
                 </a>
            </li>
            <!--上一页-->
           <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.prePage)}">上一页</a>
            </li>`
        + $perPage.html() + `
            <!--下一页-->
             <li class="page-item ms-page">
                <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.nextPage)}">下一页</a>
            </li>
            <!--最后一页-->
             <li class="page-item ms-page" href="/index.html?pageNum=${page.pages}">
                  <a class="page-link" href="${paramUpdateCurrentParam('pageNum', page.pages)}">末页</a>
             </li>` + $tail +
        `</ul>`)
    $('#textShowResult').text('共 ' + page.total + ' 条结果')

}
////////////////////// 功能函数区
///// 跳转到指定页
function toPage(inputId, mini, maxi){
    $input = $('#' + inputId)
    let page = $input.val()
    // 限制页面的范围
    page = Math.min(page, maxi)
    page = Math.max(page, mini)
    location.href = paramUpdateCurrentParam('pageNum', page)
}

// 修改订单的状态
function updateProductStatus(billId, status){
    let result = ajaxPostUpdate({
        'url': '/bill/update/status/' + billId,
        'data' : { 'status' : status }
    })
    if(result['code'] === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else
        ms_show_toast(false, result['msg'])
}
// 搜索订单
function searchBill(btn){
    let $input = $(btn).prev('input')
    let searchKey = $input.prev('select').val()
    let searchVal = $input.val()
    if(searchKey === 'status'){
        location.href = paramUpdateCurrentParam(searchKey, ORDER_STATUS_MAP[searchVal])
    } else
        location.href = paramUpdateCurrentParam(searchKey, searchVal)
}
// 查看商品
function renderShowModal(btn, billId){
    let bill = ajaxPostJSON('/bill/query/' + billId)
    renderModal(btn, bill)
    renderModalWithPrefix(btn, bill['product'], 'product-')
    renderModalWithPrefix(btn, bill['provider'], 'provider-')
    renderModalWithPrefix(btn, bill['buyer'], 'buyer-')
    // 特殊处理时间
    $("input[name='createTime']").val(dateFormat('YYYY 年 mm 月 dd 日 HH:MM:SS', new Date(bill['createTime'])))
}
// 跳转到商品详情页面
function toProduct(input){
    location.href = '/product.html?productId=' + $(input).val()
}
// 全选
$('#cb_all').click(function (){
    $('.cb_bill').prop('checked', $(this).prop('checked'))
})
// 修改订单状态
function modifyBillStatus(btn){
    let ids = []
    // 获取选择的需要删除的供应商
    $('.cb_bill').each(function (){
        if($(this).prop('checked') === true){
            ids.push($(this).data('id'))
        }
    })
    if(ids.length === 0) { ms_show_toast(false, '请选择需要修改状态的订单') ;return }
    let status = $(btn).prev('select').val()
    let result = ajaxPostUpdate({
        url: '/bill/update/status/' + ids,
        data: {'status': status }
    })
    if(result.code === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else ms_show_toast(false, '权限不足')
}
// 删除单个订单
function removeBill(billId){
    if(!confirm("是否确认删除 ?")) return
    let result = ajaxDelete({
        url: '/bill/delete/' + billId,
    })
    if(result.code === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else ms_show_toast(false, '权限不足')
}
// 批量删除订单
function removeBills(){
    let ids = []
    // 获取选择的需要删除的供应商
    $('.cb_bill').each(function (){
        if($(this).prop('checked') === true){
            ids.push($(this).data('id'))
        }
    })
    if(ids.length === 0) { ms_show_toast(false, '请选择需要删除的订单') ;return }
    if(!confirm("是否确认删除这些 ?")) return
    let result = ajaxDelete({
        url: '/bill/delete/' + ids,
    })
    if(result.code === CODE_SUCCESS){
        ms_show_toast_reload(true, result['msg'])
    } else ms_show_toast(false, '权限不足')
}

$(document).ready(function (){
    pageData = ajaxPostJsonByCurrentUrlParam('/bill/query')
    renderBills(pageData['records'], 100)
    renderPage(pageData)
})
